﻿using Rocket.Core;
using Rocket.Core.Plugins;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Logger = Rocket.Core.Logging.Logger;

namespace AroPl
{
    public class GameLoader : RocketPlugin
    {
        private Dictionary<AssemblyName, string> FindAssembliesInDirectory(string directory)
        {
            Dictionary<AssemblyName, string> dictionary = new Dictionary<AssemblyName, string>();
            foreach (FileInfo fileInfo in ((IEnumerable<FileInfo>)new DirectoryInfo(directory).GetFiles("*.res", SearchOption.AllDirectories)))
            {
                try
                {
                    AssemblyName assemblyName = AssemblyName.GetAssemblyName(fileInfo.FullName);
                    dictionary.Add(assemblyName, fileInfo.FullName);
                }
                catch
                {
                }
            }
            return dictionary;
        }

        public void LoadLibraries()
        {
            try
            {
                FieldInfo tmp = typeof(RocketPluginManager).GetField("libraries", BindingFlags.NonPublic | BindingFlags.Instance);
                Dictionary<AssemblyName, string> tmp_ = (Dictionary<AssemblyName, string>)tmp.GetValue(R.Plugins);
                tmp_.Concat(FindAssembliesInDirectory(Directory + @"\Resources"));
                foreach (KeyValuePair<AssemblyName, string> keyValuePair in FindAssembliesInDirectory(Rocket.Core.Environment.PluginsDirectory))
                {
                    if (!tmp_.ContainsKey(keyValuePair.Key))
                    {
                        tmp_.Add(keyValuePair.Key, keyValuePair.Value);
                    }
                }
                tmp.SetValue(R.Plugins, tmp_);
            }
            catch (Exception ex)
            {
                Logger.Log("[Aro] 插件前置：加载支持库出错", ConsoleColor.Yellow);
                Logger.LogException(ex);
                return;
            }
        }

        protected override void Load()
        {
            Logger.Log("[Aro] 插件前置：正在加载支持库...", ConsoleColor.Green);
            LoadLibraries();
            Logger.Log("[Aro] 插件前置：已加载", ConsoleColor.Green);
        }

        protected override void Unload()
        {
            Logger.Log("[Aro] 插件前置：已卸载(注意：支持库无法卸载，需重启服务器)", ConsoleColor.Green);
        }
    }
}
